package com.cardbaobao.cardbabyclient.ui.fragment.collect;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.LoansDetailActivity;
import com.cardbaobao.cardbabyclient.ui.activity.SpeedLoanActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.FlowCommonAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.FlowLayout;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/7/5 18:47.
 */

public class CollectLoanFragment extends BaseFragment {
    private String prePageId;

    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }

    private static final int PAGE_START=1;
    private int page=PAGE_START;
    private boolean isLoading;
    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private LoanAdapter adapter;

    private boolean canLoadMore=true;

    private List<LoanBean> data=new ArrayList<>();
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_collect;
    }

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_collected_loan_page;

        footerLoadMore.setStateNoMoreDataStr("没有更多数据了");
        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                loadData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page=PAGE_START;
                loadData();
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter=new LoanAdapter();

        loadData();
    }

    private void loadData(){
        if(isLoading){
            return;
        }
        showProgressDialog(false);
        isLoading=true;
        Observable<String> observable=
                Api.collectedLoan("ZCC0102",
                        String.valueOf(mApplication.getUser().getID()),
                        String.valueOf(page),
                        String.valueOf(Constant.SIZE));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                isLoading=false;
                dismissProgressDialog();
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                if(canLoadMore){
                    footerLoadMore.setStatePreLoading();
                    srLayout.setLoadmoreFinished(false);
                }else{
                    footerLoadMore.setStateNoMoreData();
                    srLayout.setLoadmoreFinished(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                page--;
                if(page<PAGE_START){
                    page=PAGE_START;
                }
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                JSONObject json= JSON.parseObject(s);
                if(json!=null){
                    if(json.getIntValue("code")==1){
                        List<LoanBean> temp=null;
                        JSONArray array=json.getJSONArray("data");
                        if(array!=null){
                            if(array.size()>0){
                                temp=new ArrayList<>();
                                JSONObject object;
                                LoanBean bean;
                                for(int i=0,size=array.size();i<size;i++){
                                    object=array.getJSONObject(i);
                                    bean=new LoanBean();
                                    bean.setApplyNum(object.getString("applyNum"));
                                    bean.setTitle(object.getString("title"));
                                    bean.setId(object.getIntValue("id"));
                                    bean.setLogoUrl(object.getString("logoUrl"));
                                    bean.setMonthRate(object.getString("monthRate"));
                                    bean.setLoansLimit(object.getString("loansLimit"));
                                    bean.setTags(JSON.parseArray(object.getString("tags"),String.class));
                                    temp.add(bean);
                                }
                                canLoadMore=true;
                            }else{
                                canLoadMore=false;
                            }
                        }
                        if(temp!=null){
                            if(page==PAGE_START){
                                data.clear();
                            }
                            if(temp.size()>0){
                                data.addAll(temp);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }else{
                        ToastUtil.showToast(json.getString("result"));
                    }
                }
            }
        });
    }

    private class LoanBean {
        /**
         * monthRate : 月利率0.1-0.11%
         * id : 100080
         * title : 房金所
         * loansLimit : 贷款额度1.0-22.0万
         * applyNum : 0人申请
         * logoUrl : /uploadFiles/uploadImgs/loans/20170526/805730357f1e41c1aba813f553776493.jpg
         * tags : ["分期还款","房屋抵押"]
         */

        private String monthRate;
        private int id;
        private String title;
        private String loansLimit;
        private String applyNum;
        private String logoUrl;
        private List<String> tags;

        public String getMonthRate() {
            return monthRate;
        }

        public void setMonthRate(String monthRate) {
            this.monthRate = monthRate;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getLoansLimit() {
            return loansLimit;
        }

        public void setLoansLimit(String loansLimit) {
            this.loansLimit = loansLimit;
        }

        public String getApplyNum() {
            final String reg="[^0-9]";
            final Pattern pattern = Pattern.compile(reg);
            final Matcher matcher=pattern.matcher(this.applyNum);
            return matcher.replaceAll("").trim();
        }

        public void setApplyNum(String applyNum) {
            this.applyNum = applyNum;
        }

        public String getLogoUrl() {
            return logoUrl;
        }

        public void setLogoUrl(String logoUrl) {
            this.logoUrl = logoUrl;
        }

        public List<String> getTags() {
            return tags;
        }

        public void setTags(List<String> tags) {
            this.tags = tags;
        }
    }

    private class ContentHolder extends RecyclerView.ViewHolder{
        private TextView tvTitle;
        private ImageView image;
        private TextView tvMarketingOne;
        private FlowLayout flLabel;
        private TextView tvApplyCount;
        private ContentHolder(View itemView){
            super(itemView);
            tvTitle= (TextView) itemView.findViewById(R.id.tv_title);
            image= (ImageView) itemView.findViewById(R.id.iv_pic);
            tvMarketingOne = (TextView) itemView.findViewById(R.id.tv_marketing_one);
            flLabel= (FlowLayout) itemView.findViewById(R.id.fl_label);
            tvApplyCount= (TextView) itemView.findViewById(R.id.tv_number);
        }
    }

    private class NoDataHolder extends RecyclerView.ViewHolder{
        private TextView tvView;
        private NoDataHolder(View itemView){
            super(itemView);
            tvView= (TextView) itemView.findViewById(R.id.tv_view);
        }
    }

    private class LoanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        private static final int TYPE_CONTENT=1;
        private static final int TYPE_NO_DATA=2;
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater=LayoutInflater.from(parent.getContext());
            if(viewType==TYPE_CONTENT){
                View itemView= inflater.inflate(R.layout.item_collect_loan,parent,false);
                return new ContentHolder(itemView);
            }
            if(viewType==TYPE_NO_DATA){
                View itemView=inflater.inflate(R.layout.item_collect_no_data,parent,false);
                return new NoDataHolder(itemView);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if(holder instanceof ContentHolder){
                if(position==0){
                    RecyclerView.MarginLayoutParams params=
                            (RecyclerView.MarginLayoutParams) holder.itemView.getLayoutParams();
                    params.topMargin= DensityUtil.dp2px(15);
                }
                final LoanBean bean=data.get(position);
                ContentHolder contentHolder= (ContentHolder) holder;
                contentHolder.tvTitle.setText(bean.getTitle());
                contentHolder.tvMarketingOne.setText(bean.getMonthRate()+","+bean.getLoansLimit());
                List<String> tags=bean.getTags();
                //去空
                List<String> temp=new ArrayList<>();
                for(String s:tags){
                    if(!TextUtils.isEmpty(s)){
                        temp.add(s);
                    }
                }
                List<String> finalStrList;
                if(temp.size()>3){
                    finalStrList=temp.subList(0,3);
                }else{
                    finalStrList=temp;
                }
                contentHolder.flLabel.setAdapter(
                        new FlowCommonAdapter(mContext,
                                finalStrList,
                                R.layout.item_speed_loan_label_gv));

                contentHolder.tvApplyCount.setText(bean.getApplyNum());
                ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL+bean.getLogoUrl(),
                        contentHolder.image,R.mipmap.img_default_square);
                contentHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_collect_loan_item,
                                Self.Action.app_click_mine_collect_loan_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        Intent intent=new Intent(mContext,LoansDetailActivity.class);
                        intent.putExtra(LoansDetailActivity.LOANS_ID_S,
                                String.valueOf(bean.getId()));
                        intent.putExtra(LoansDetailActivity.LOANS_NAME_S,
                                bean.getTitle());
                        intent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(intent);
                    }
                });
            }
            if(holder instanceof NoDataHolder){
                ((NoDataHolder) holder).tvView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_collect_loan_view_other,
                                Self.Action.app_click_mine_collect_loan_view_other_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        initIntent();
                        mIntent.setClass(mContext,SpeedLoanActivity.class);
                        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                        getActivity().finish();
                    }
                });
            }
        }

        @Override
        public int getItemViewType(int position) {
            return data.size()==0?TYPE_NO_DATA:TYPE_CONTENT;
        }

        @Override
        public int getItemCount() {
            return data.size()==0?1:data.size();
        }
    }
}
